package smartt.styy.auth.service.impl;

import smartt.styy.auth.constants.ServerConstants;
import smartt.styy.auth.model.jwt.IJWTInfo;
import smartt.styy.auth.model.jwt.JWTInfo;
import smartt.styy.auth.model.request.JwtAuthenticationRequest;
import smartt.styy.auth.model.request.VerifyTokenReq;
import smartt.styy.auth.model.response.JwtUserInfoRsp;
import smartt.styy.auth.model.utils.JwtTokenUtil;
import smartt.styy.auth.service.AuthService;
import smartt.styy.auth.service.UserService;
import smartt.styy.auth.util.DESEncrypt;
import smartt.styy.common.bean.UserInfo;
import smartt.styy.common.exception.auth.UserInvalidException;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    private JwtTokenUtil jwtTokenUtil;
    
    private UserService userService;
    
    @Value("${3des.key}")
	private String desKey;
    

    @Override
    public Map<String,Object> login(JwtAuthenticationRequest authenticationRequest) throws Exception {
    	Map<String,Object> restMap = new HashMap<String,Object>();
    	UserInfo info = userService.validate(authenticationRequest);
        if (!StringUtils.isEmpty(info.getId())) {
        	String jwt = jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getNickName(),info.getUserTypes(),info.getTelPhone()));
        	restMap.put("userId", DESEncrypt.encryptMode(desKey,info.getId()));
        	restMap.put("token", jwt);
        	restMap.put("userType", authenticationRequest.getUserType());
        	return restMap;
        }
        log.error("[AuthService][login]用户登录，用户不存在或账户密码错误!");
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }

    @Override
    public JwtUserInfoRsp validate(VerifyTokenReq param) throws Exception {
    	IJWTInfo res = jwtTokenUtil.getInfoFromToken(param.getToken());
    	
    	String userId = DESEncrypt.encryptMode(desKey,res.getId());
    	//判断userId，userType 和传入进来的是否一致
    	boolean verifty = true;
    	Integer userType = Integer.parseInt(res.getUserTypes());
    	if(param.getUserType() == ServerConstants.USER_TYPE_1 || param.getUserType() == ServerConstants.USER_TYPE_4){
    		verifty = false;
    	}
    	if(verifty){
    		if(!userId.equals(param.getUserId())){
    			return null;
    		}
    		if(res.getUserTypes() != null && !res.getUserTypes().equals(param.getUserType().toString())){
    			return null;
    		}
    	}
    	
    	JwtUserInfoRsp jwtUser = new JwtUserInfoRsp();
    	jwtUser.setUserId(userId);
    	jwtUser.setUsername(res.getUniqueName());
    	jwtUser.setUserTypes(userType);
    	jwtUser.setEffectiveTime(res.getEffectiveTime());
    	jwtUser.setNickName(res.getNickName());
    	return jwtUser;
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }
}
